package trlygjj.tanruiliyigenjinjin.util;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by user on 2018/7/13.
 */
//切入到所有的Controller中
@ControllerAdvice
public class ExceptionsHandler {
    //专门用来处理shiro的没有权限异常的方法
    @ExceptionHandler(UnauthorizedException.class)
    public void exceptionHandler(HandlerMethod hm, HttpServletResponse response) throws IOException {
        //分情况进行处理,ajax不跳转页面,普通请求跳转页面
        ResponseBody body = hm.getMethodAnnotation(ResponseBody.class);
        if(body != null){
            //System.out.println("没有权限的ajax就看得到我!");
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write("{\"success\":false,\"msg\":\"没有执行当前操作的权限!\",\"total\":0,\"rows\":[]}");
        }else{
            response.setContentType("text/html;charset=utf-8");
            response.sendRedirect("/nopermission.jsp");
        }
    }
}
